import Taro from '@tarojs/taro'

export default function request  (options = {}) {
  const { method, url, data, requestType, auth = true, headers, showToast = true } = options;
  const contentType = requestType ==='form' ? 'application/x-www-form-urlencoded' : 'application/json';
  let header = {'content-type': contentType};
  return new Promise((resolve, reject) => {
    Taro.request({
      url: `${window.location.protocol}//${window.location.host}/${url}`,
      method,
      data,
      dataType: 'json',
      header
    }).then((res) => {
      if (res.header && res.header['RefreshToken']) {
        //更新快过期的token
        Taro.setStorageSync('token', res.header['RefreshToken'])
      }
      const data = res.data;
      if (data.flag) {
        resolve(data)
      } else {
        showToast && Taro.showToast({
          title: `[${data.status}] ${data.error}`,
          icon: 'none',
          duration: 2000
        });
        reject(data)
      }
    })
  })
}
